package com.self.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class UdpClient {

    public static void main(String[] args) {

        try {

            for (int i = 0; i< 5;i++) {
                DatagramSocket cl = new DatagramSocket();
                new Client(cl,3000,"客户端-"+i).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class Client {
        int port;
        Runnable command;
        String name;
        DatagramSocket udpSocket;
        Client(DatagramSocket udpSocket,int remotePort,String name) {
            this.udpSocket = udpSocket;
            this.name = name;
            this.port = remotePort;
        }

        public void start() {

            try {
                new Thread(() -> {

                    try {

                        while (true) {


                            // send data
                            String dataStr = String.format("端口:%s",udpSocket.getLocalSocketAddress());
                            byte[] data = dataStr.getBytes();

                            DatagramPacket sendPacket = new DatagramPacket(data,0,data.length,new InetSocketAddress("localhost",port));
                            udpSocket.send(sendPacket);



                            // recv response
                            byte[] buf = new byte[1024*1024];
                            DatagramPacket recv = new DatagramPacket(buf,0,buf.length);
                            udpSocket.receive(recv);

                            String c = new String(recv.getData(),0,recv.getLength());

                            System.out.println(String.format("线程: %s\n-----------------------------------------\n请求: >>>> %s\n响应: >>>> %s",Thread.currentThread().getName(),dataStr,c));


                            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                },name).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
